package com.tange.ai.core.demo;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.tange.ai.core.demo.databinding.ActivityLoginBinding;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.core.backend.service.http.HttpConfigurations;
import com.tange.core.backend.service.request.Http;
import com.tange.core.backend.service.request.HttpResponse;
import com.tange.core.initialization.Socket;
import com.tange.core.initialization.TGCore;

import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends AppCompatActivity {

    public static final String PRE_USER_NAME = "PRE_USER_NAME";
    public static final String PRE_USER_PWD = "PRE_USER_PWD";

    private ActivityLoginBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getSupportActionBar().hide();

        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            uiFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.getDecorView().setSystemUiVisibility(uiFlags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        Utils.setStatusBar(this, Color.TRANSPARENT);

        binding.login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestUserToken(binding.username.getText().toString().trim(), binding.password.getText().toString().trim());
            }
        });

        String userName = PreferenceUtil.getString(this, PRE_USER_NAME, "");
        String userPwd = PreferenceUtil.getString(this, PRE_USER_PWD, "");

        if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userPwd)) {
            binding.username.setText(userName);
            binding.password.setText(userPwd);

            requestUserToken(userName, userPwd);
        }
    }

    private void setUser(String token, String id) {
        int userId = Integer.parseInt(id);

        if (!TextUtils.isEmpty(token)) {

            HttpConfigurations.getInstance().setUserId(userId);
            HttpConfigurations.getInstance().setUserToken(token);
            Socket.INSTANCE.launch(userId);

            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    private void requestUserToken(String userName, String password) {

        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
            Toast.makeText(this, "用户名或者密码为空", Toast.LENGTH_LONG).show();
            return;
        }

        HashMap<String, String> loginMap = new HashMap<>();
        loginMap.put("username", userName);
        loginMap.put("pwd", password);

        // 以下登录过程仅做DEMO演示，沿用了探鸽账号体系。
        // 实际上，接入方需要自行对接探鸽后台API，以获取 用户 token信息
        HttpConfigurations.getInstance().setPackageName("com.tange365.icam365");
        Http.INSTANCE.create().path("/app/user/login").param("username", userName).param("pwd", password).post().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<HttpResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HttpResponse response) {
                        if (response.isSuccess()) {

                            PreferenceUtil.setString(LoginActivity.this, PRE_USER_NAME, userName);
                            PreferenceUtil.setString(LoginActivity.this, PRE_USER_PWD, password);

                            setUser(response.asJsonObject().get("token").getAsString(), response.asJsonObject().get("id").getAsString());
                        } else {
                            Toast.makeText(LoginActivity.this, "Failed:  " + response.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(LoginActivity.this, "onError:  " + e, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}